#include "flash.h"
#include "global.h"
u8 g_bFlashStatus=SUCCESS;
//u16 hwBuffer1[PAGE_SIZE/2];   
//u16 hwBuffer2[PAGE_SIZE/2];

u16 Flash_ReadHalfWord(u32 wAddr)
{
	return *(vu16*)wAddr; 
}
u32 Flash_ReadWord(u32 wAddr)
{
	return *(vu32*)wAddr; 
}

void Flash_Write(u32 wAddr, u32 *pBuffer, u16 hwNum2Write)
{
	u32 wAddrTemp=wAddr;
	u16 i;
	
	RCC_AHBPeriphClockCmd(RCC_AHBPERIPH_FLASH, ENABLE);
	FLASH_ClearFlag(FLASH_FLAG_PRGMFLR);
	
	FLASH_Unlock();

	for(i=0; i<hwNum2Write/4; i++)
	{
		//FLASH_ProgramHalfWord(wAddrTemp, pBuffer[i]);
		//wAddrTemp += 2;
		FLASH_ProgramWord(wAddrTemp,pBuffer[i]);
		wAddrTemp += 4;
	}
	
	FLASH_Lock();
}

void Flash_Read(u32 wAddr, u32 *pBuffer, u16 hwNum2Read)
{
	u32 wAddrTemp=wAddr;
	u16 i;
	
	for(i=0; i<hwNum2Read/4; i++)
	{
		//pBuffer[i] = Flash_ReadHalfWord(wAddrTemp);
		//wAddrTemp += 2;	
		pBuffer[i] = Flash_ReadWord(wAddrTemp);		
		wAddrTemp += 4;	
	}
}
#if 0
void FLASH_Update(void)
{
	u16 i;
	u32 wPageNum=APP_SIZE/PAGE_SIZE;
	u32 wPageCnt=0;
	u32 wAddrOffset;
	
	g_bFlashStatus=SUCCESS;
	FLASH_Unlock();
	do{
		wAddrOffset = wPageCnt*PAGE_SIZE;
		Flash_Read(FLASH_BKP_ADDR+wAddrOffset, hwBuffer1, PAGE_SIZE/2);
		FLASH_ErasePage(FLASH_APP_ADDR+wAddrOffset);
		Flash_Write(FLASH_APP_ADDR+wAddrOffset, hwBuffer1, PAGE_SIZE/2);
		Flash_Read(FLASH_APP_ADDR+wAddrOffset, hwBuffer2, PAGE_SIZE/2);

		for(i=0; i<(PAGE_SIZE/2); i++)
		{
			if(hwBuffer1[i] != hwBuffer2[i])
			{
				g_bFlashStatus = ERROR;
				break;
			}
		}
		wPageCnt++;
	}while(wPageCnt < wPageNum);
	FLASH_Lock();
}
#endif

